import dayjs from "dayjs";
// import { gpsToAMap } from '@/utils/AMap/mapTools';
import { message } from "antd";
import { getItem } from "@/utils/localstorage";
import { useRouteProps } from "umi";
export const handleLnglat = async (res) => {
  const arr1 = [];
  const arr2 = [];
  res.forEach((it) => {
    arr1.push({
      positionAmap: it.positionAmap || it.positionOriginal,
      time: dayjs(+it.toUpdateTimeStamp).format("HH:mm:ss"),
      direction: it.direction,
    });
    arr2.push(it.positionAmap?.split(",") || it.positionOriginal?.split(","));
  });

  return {
    arrhasTime: arr1 || [],
    arrPure: arr2 || [],
  };
};

export const handleLnglatCar = async (res) => {
  const arr1 = [];
  const arr2 = [];
  res.forEach((it) => {
    arr1.push({
      positionAmap: `${it.longitude},${it.latitude}`,
      time: dayjs(it.dateTime).format("HH:mm:ss"),
    });
    arr2.push([it.longitude, it.latitude]);
  });

  return {
    arrhasTime: arr1 || [],
    arrPure: arr2 || [],
  };
};

export const downloadHandle = async (
  res,
  name = dayjs().format("YYYY-MM-DD HH:mm:ss")
) => {
  const reader = new FileReader();
  reader.readAsText(res);
  reader.onload = (result) => {
    try {
      let resData = JSON.parse(result.target.result);
      if (resData.code) {
        message.error(resData.msg);
      }
    } catch (err) {
      const blob = new Blob([res]); //二进制数据流
      const objectURL = URL.createObjectURL(blob);
      let btn = document.createElement("a");
      btn.download = `${name}.xlsx`; //文件类型
      btn.href = objectURL;
      btn.click();
      URL.revokeObjectURL(objectURL);
      btn = null;
    }
  };
};

export const updateTreeData = (list, key, children) => {
  return list.map((node) => {
    if (node.id === key) {
      return {
        ...node,
        children,
      };
    }
    if (node.children) {
      return {
        ...node,
        children: updateTreeData(node.children, key, children),
      };
    }
    return node;
  });
};

// 窗口内容
export const createInfoWindow = (title, content, map) => {
  let info = document.createElement("div");
  info.className = "custom-info input-card content-window-card";
  // 定义顶部标题
  let top = document.createElement("div");
  let titleD = document.createElement("div");
  let closeX = document.createElement("img");
  top.className = "info-top";
  closeX.className = "info-close-img";
  titleD.innerHTML = title;
  closeX.src = "https://webapi.amap.com/images/close2.gif";
  closeX.onclick = () => map.clearInfoWindow();

  top.appendChild(titleD);
  top.appendChild(closeX);
  info.appendChild(top);

  // 定义中部内容
  let middle = document.createElement("div");
  middle.className = "info-middle";
  middle.style.backgroundColor = "white";
  middle.innerHTML = content;
  info.appendChild(middle);

  // 定义底部内容
  let bottom = document.createElement("div");
  bottom.className = "info-bottom";
  bottom.style.position = "relative";
  bottom.style.top = "0px";
  bottom.style.margin = "0 auto";
  let sharp = document.createElement("img");
  sharp.src = "https://webapi.amap.com/images/sharp.png";
  bottom.appendChild(sharp);
  info.appendChild(bottom);
  return info;
};

// 解决树的key重复问题
export const treeAddKey = (list) => {
  const treeList = [...list];
  treeList.forEach((item) => {
    item.value = item.key ? item.id : `dept-${item.id}`;
    if (!item.key) {
      item.disabled = true;
    }
    if (item.children) {
      treeAddKey(item.children);
    }
  });

  return treeList;
};

/**
 * 得到随即颜色
 * @returns eg: #F0A3C7
 */
export const getRandomColor = () => {
  const letters = "0123456789ABCDEF";
  let color = "#";
  for (let i = 0; i < 6; i++) {
    color += letters[Math.floor(Math.random() * 16)];
  }
  return color;
};

/**
 * 会员详情卡余额展示
 *
 */
export const vipTypeList = {
  1: { text: "储值卡", status: "元", shortName: "储值" },
  2: { text: "期限卡", status: "课时", shortName: "期限" },
  3: { text: "次数卡", status: "次", shortName: "次数" },
};

export const effectiveTypeList = {
  1: { text: "天" },
  2: { text: "月" },
  3: { text: "年" },
};

export const VipCategoryEnum = {
  1: { text: "正式卡", shortName: "正式" },
  2: { text: "体验卡", shortName: "体验" },
};

/**禁止选之前的日期 *
 */
// eslint-disable-next-line arrow-body-style
export const disabledDate = (current) => {
  // Can not select days before today and today
  return current && current < dayjs().startOf("day");
};

export const disabledDateEnd = (current) => {
  // Can not select days before today and today
  return current && current > dayjs().startOf("day");
};

export const webSocketUrl = process.env.UMI_WEBSOCKETURL;

//判断时间间隔
export const timeago = (val) => {
  var minute = 1000 * 60; //把分，时，天，周，半个月，一个月用毫秒表示
  var hour = minute * 60;
  var day = hour * 24;
  var week = day * 7;
  var month = day * 30;
  var now = new Date().getTime(); //获取当前时间毫秒
  var dateTimeStamp = new Date(val).getTime();
  var diffValue = now - dateTimeStamp; //时间差
  var result;
  if (diffValue < 0) {
    return;
  }
  var minC = diffValue / minute; //计算时间差的分，时，天，周，月
  var hourC = diffValue / hour;
  var dayC = diffValue / day;
  var weekC = diffValue / week;
  var monthC = diffValue / month;
  if (monthC >= 1 && monthC <= 3) {
    result = " " + parseInt(monthC) + "月前";
  } else if (weekC >= 1 && weekC <= 3) {
    result = " " + parseInt(weekC) + "周前";
  } else if (dayC >= 1 && dayC <= 6) {
    result = " " + parseInt(dayC) + "天前";
  } else if (hourC >= 1 && hourC <= 23) {
    result = " " + parseInt(hourC) + "小时前";
  } else if (minC >= 1 && minC <= 59) {
    result = " " + parseInt(minC) + "分钟前";
  } else if (diffValue >= 0 && diffValue <= minute) {
    result = "刚刚";
  } else {
    result = val;
  }
  return result;
};

//判断页面有哪些按钮权限
export const getBtnAccess = () => {
  let pathName = useRouteProps().path;
  let Access = getItem("permissions") || [];
  let hasAccessList = Access.filter(function (o) {
    return o.parentPath == pathName;
  });
  let btnList = [];
  if (hasAccessList && hasAccessList.length > 0) {
    if (
      hasAccessList[0].buttonPermsVoList &&
      hasAccessList[0].buttonPermsVoList.length > 0
    ) {
      hasAccessList[0].buttonPermsVoList.map((item) => {
        btnList.push(item.perms);
      });
    }
    return btnList;
  } else {
    return [];
  }
};
